package com.sp.scmdb.serviceImpl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sp.scmdb.bean.TitleBean;
import com.sp.scmdb.bean.UserBean;
import com.sp.scmdb.common.CommonParamter;
import com.sp.scmdb.dao.TitleDao;
import com.sp.scmdb.entity.Title;
import com.sp.scmdb.service.LogService;
import com.sp.scmdb.service.TitleService;

@Service("titleService")
public class TitleServiceImpl implements TitleService {

	private TitleDao titleDao;
	private LogService logs;

	public void setLogs(LogService logs) {
		this.logs = logs;
	}
	
	public void setTitleDao(TitleDao titleDao) {
		this.titleDao = titleDao;
	}

	@Transactional(readOnly = true)
	public List<Title> queryAll() {
		return titleDao.queryAll();
	}

	@Transactional
	public String newTitle(TitleBean t, UserBean user) {
		String result="3";
		StringBuffer Hql = new StringBuffer("from Title where 1=1 ");
		if (StringUtils.isNotEmpty(t.getName())) {
			Hql.append("and name='").append(t.getName()).append("'");
			List<Title> list = titleDao.queryHql(Hql.toString());
			if (CollectionUtils.isEmpty(list)) {
				Title title = new Title();
				title.setName(t.getName());
				titleDao.save(title);
				logs.addLog(user, "添加  职称：\""+t.getName()+"\"成功！");	
				result = CommonParamter.CHECK_SUCCESS;
			}
			else{
				result = CommonParamter.CHECK_REPEAT;
			}
		}
		return result;
	}

	@Transactional
	public String editTitle(TitleBean bean, UserBean user) {
		String result = "2";
		// 检查职称名称是否重复
		if (StringUtils.isNotEmpty(bean.getName())) {
			StringBuffer Hql = new StringBuffer();
			Hql.append("from Title where id != " + bean.getId()
					+ " and name = '" + bean.getName() + "'");
			if (CollectionUtils.isEmpty(titleDao.queryHql(Hql.toString()))) {
				Title title = titleDao.getById(Integer.parseInt(bean.getId()));
				// 如果名称没有重复的
				title.setName(bean.getName());
				// 保存该职称
				titleDao.update(title);
				logs.addLog(user, "修改  职称：\""+bean.getName()+"\"成功！");	
				result = CommonParamter.CHECK_SUCCESS;
			} else {
				result = CommonParamter.CHECK_REPEAT;
			}
		}
		return result;
	}

	@Transactional
	public String delTitle(String[] ids, UserBean user){
		String result="1";
		Title title = null;
		for (int i = 0; i < ids.length; i++) {
			title = titleDao.getById(Integer.parseInt(ids[i]));
			if (title != null) {
				logs.addLog(user, "删除  职称：\""+title.getName()+"\"成功！");	
				// 删除职称信息
				titleDao.delete(title);
				
				result = CommonParamter.CHECK_SUCCESS;
			}
		}
		return result;
	}

	@Transactional(readOnly = true)
	public Title findID(String depId) {
		
		return titleDao.getById(Integer.parseInt(depId));
	}
}
